import React, { useState, useRef, useEffect } from 'react';
import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { t } from '@lingui/macro';
import { Button, Drawer, Message, Tab } from '@alifd/next';
import { useStore } from '@/hooks';
import { uniqueId } from 'lodash';
import { column, toSelectDataSource, ENUMS } from './stores/definitions';
import { observer } from 'mobx-react-lite';
import { toJS } from 'mobx';
import BusOrderForm from '@/pages/order/BusOrder/components/BusOrderForm';
import ScOrderForm from '@/pages/order/ScOrder/components/ScOrderForm';
import CcOrderForm from '@/pages/order/CcOrder/components/CcOrderForm';
import RsOrderForm from '@/pages/order/RsOrder/components/RsOrderForm';

const tableId = uniqueId('tauTable-');

const Refund = () => {
  const { refundStore: store } = useStore();
  const [modal, setModal] = useState([]);
  const [isView, setIsView] = useState([]);
  const refundRef = useRef();

  useEffect(() => {
    return () => {
      store._orderStatus = '0';
    };
  }, []);

  /**
   * @description 处理搜索条件
   * @param {*} params
   */
  const handleOnSearch = (params) => {
    const { orderDate, orderType, ...searchArgs } = params.values;
    const { from, to } = orderDate || [];
    store.search = {
      from,
      to,
      orderType,
      ...searchArgs,
    };
  };

  /**
   * 驳回退款
   * @param {*} result
   */
  const handleOnReject = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        const { refundId, applicationId, refund } = toJS(result);
        await store.onReject({ refundId, applicationId, rejectRemark: refund.refundRemark });
        Message.success({ content: t`驳回成功` });
      } catch (e) {
        Message.error({ content: t`驳回失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  /**
   * 关闭侧边卡片
   */
  const handleCancel = () => {
    setModal([]);
    setIsView([]);
  };

  // 点击打开查看
  const handleViewOrderInfo = (order) => {
    const { orderType } = order?.orderInfo;
    refundRef.current = order;
    if (orderType === 1) {
      return setModal(['view']);
    }
    setModal([orderType]);
  };

  // 点击打开退款
  const handleRefund = (order) => {
    refundRef.current = order;
    setModal(['refund']);
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        searchItems={[
          {
            name: 'orderDate',
            type: 'date-range',
            props: {
              placeholder: [t`退款起始时间`, t`退款结束时间`],
            },
          },
          {
            name: 'state',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.state),
              placeholder: t`申请状态`,
            },
          },
          {
            name: 'type',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.refundType),
              placeholder: t`退款类型`,
            },
          },
        ]}
        keywordSearch={{
          // enabled: false,
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <div className="content">
        <Tab
          activeKey={store.orderStatus}
          onChange={(v) => { store.orderStatus = v; }}
        >
          {ENUMS.TABS_ITEMS.map((item) => (<Tab.Item key={item.key} title={item.label} />))}
        </Tab>
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.refund)}
          columns={[
            { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('orderInfo.orderId', {
              width: 200,
              cell: (v, __, order) => {
                return <Button text type="primary" onClick={() => handleViewOrderInfo(order)}>{v}</Button>;
              },
            }),
            column('applicationId', { width: 120 }),
            column('orderInfo.name', { width: 88 }),
            column('type', { width: 100 }),
            column('state', { width: 88 }),
            column('cancelTime', { width: 180 }),
            column('refundTime', { width: 180 }),
            column('refundPrice', { width: 100 }),
            column('cancelRemark', { width: 180 }),
          ]}
        />
      </div>
      <Drawer
        visible={!!modal[0]}
        title={ENUMS.TYPE_TEXT[refundRef.current?.type]}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width={'90%'}
      >
        {modal[0] === 'view' && <CcOrderForm
          modal={modal}
          isView={isView}
          orderId={refundRef.current?.orderInfo?.orderId}
          handleCancel={() => handleCancel()}
          onSubmit={handleRefund}
          onReject={handleOnReject}
        />}
        {modal[0] === 2 && <ScOrderForm
          modal={modal}
          isView={isView}
          orderId={refundRef.current?.orderInfo?.orderId}
          onCancel={() => handleCancel()}
          onSubmit={handleRefund}
          onReject={handleOnReject}
        />}
        {modal[0] === 3 && <BusOrderForm
          modal={modal}
          isView={isView}
          orderId={refundRef.current?.orderInfo?.orderId}
          onCancel={() => handleCancel()}
          onSubmit={handleRefund}
          onReject={handleOnReject}
        />}
        {modal[0] === 4 && <RsOrderForm
          modal={modal}
          isView={isView}
          orderId={refundRef.current?.orderInfo?.orderId}
          onCancel={() => handleCancel()}
          onSubmit={handleRefund}
          onReject={handleOnReject}
        />}
      </Drawer>
    </TauPage>
  );
};

export default observer(Refund);
